using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

[Serializable]
public class Machinery
{
    public string code;
    public string success;
    public MachineryData data;
}

[Serializable]
public class MachineryData
{
    public int idleMachinery;
    public int[] useMachineryByYear;
    public int allMachinery;
    public int[] useMachineryByMonth;
    public int useMachinery;
    public int abnormalMachinery;
}

public class RequestAPIController : MonoBehaviour
{
    private string 查看设备使用情况地址 = "http://192.168.22.62:9888/system/equipment/selectMachineryStatistics.action";

    private string 文件上传地址 = "http://192.168.22.62:9888/system/equipment/uploadFile.action";

    private string token = "";

    private string imagePath = Application.streamingAssetsPath + "/1.jpg";

    private void Start()
    {
        StartCoroutine(SendGetRequestWithoutParams(查看设备使用情况地址, token));

        StartCoroutine(UploadFile(imagePath, 文件上传地址, token));
    }

    /// <summary>
    /// 上传文件到服务器
    /// </summary>
    /// <param name="filePath">要上传的文件路径</param>
    /// <param name="uploadURL">服务器的上传地址</param>
    /// <param name="token">身份验证 Token</param>
    private IEnumerator UploadFile(string filePath, string uploadURL, string token)
    {
        if (!File.Exists(filePath))
        {
            Debug.LogError($"文件不存在: {filePath}");
            yield break; // 终止协程
        }

        WWWForm form = new WWWForm();
        byte[] fileData = File.ReadAllBytes(filePath);
        string fileName = Path.GetFileName(filePath);

        form.AddBinaryData("file", fileData, fileName);
        Debug.Log($"准备上传文件: {fileName}");

        using (UnityWebRequest request = UnityWebRequest.Post(uploadURL, form))
        {
            request.SetRequestHeader("Authorization", token);

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"文件上传失败: {request.error}");
            }
            else
            {
                Debug.Log($"文件上传成功！服务器返回: {request.downloadHandler.text}");
            }
        }
    }

    /// <summary>
    /// 从指定 URL 下载文件并保存到本地
    /// </summary>
    /// <param name="downloadURL">文件下载地址</param>
    /// <param name="savePath">本地保存路径（完整路径，包括文件名）</param>
    private IEnumerator DownloadFile(string downloadURL, string savePath)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(downloadURL))
        {
            request.downloadHandler = new DownloadHandlerFile(savePath)
            {
                removeFileOnAbort = true // 失败时自动删除未完成的文件
            };

            // 发送请求并等待下载完成
            yield return request.SendWebRequest();

            // 检查是否有错误发生
            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log($"下载成功！文件保存到: {savePath}");
            }
            else
            {
                Debug.LogError($"下载失败: {request.error}");
            }
        }
    }

    /// <summary>
    /// 📊 导出 Excel 文件
    /// </summary>
    /// <param name="url">API 地址</param>
    /// <param name="param">请求参数</param>
    /// <param name="fileName">保存的文件名</param>
    /// <param name="token">API 访问 Token</param>
    private IEnumerator ExportExcelFile(string url, string param, string fileName, string token)
    {
        WWWForm form = new WWWForm();
        form.AddField("param", param);

        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            request.SetRequestHeader("Authorization", token);

            // 发送请求并等待返回
            yield return request.SendWebRequest();

            string response = request.downloadHandler.text;

            // 处理返回结果
            if (request.result == UnityWebRequest.Result.Success)
            {
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                string filePath = desktopPath + $"/{fileName}.xlsx";

                // 将字节数组写入文件
                File.WriteAllBytes(filePath, request.downloadHandler.data);

                Debug.Log("Excel文件保存成功：" + filePath);
            }
            else
            {
                Debug.LogError("请求出错: " + request.error + " , 错误信息: " + response);
            }
        }
    }

    /// <summary>
    /// 📨 发送 POST 请求
    /// </summary>
    /// <param name="url">API 地址</param>
    /// <param name="param1">参数1</param>
    /// <param name="param2">参数2</param>
    /// <param name="token">API 访问 Token</param>
    private IEnumerator SendPostRequest(string url, string param1, string param2, string token)
    {
        WWWForm form = new WWWForm();
        form.AddField("param1", param1);
        form.AddField("param2", param2);

        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            request.SetRequestHeader("Authorization", token);

            // 发送请求并等待返回
            yield return request.SendWebRequest();

            string response = request.downloadHandler.text;

            // 处理返回结果
            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("POST 请求成功, 返回数据: " + response);

                Machinery machinery = JsonUtility.FromJson<Machinery>(response);
            }
            else
            {
                Debug.LogError("POST 请求出错: " + request.error + " , 错误信息: " + response);
            }
        }
    }

    /// <summary>
    /// 发送 GET 请求（带参数）
    /// </summary>
    private IEnumerator SendGetRequestWithParams(string baseUrl, string param1, string param2, string token)
    {
        // 拼接参数到URL上
        //string url = baseUrl + "?param1=" + param1 + "&param2=" + param2; // 方法一

        string url = $"{baseUrl}?param1={param1}&param2={param2}"; // 方法二

        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            request.SetRequestHeader("Authorization", token);

            yield return request.SendWebRequest();

            string response = request.downloadHandler.text;

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("GET（带参数）请求成功, 返回数据: " + response);

                Machinery machinery = JsonUtility.FromJson<Machinery>(response);
            }
            else
            {
                Debug.LogError("GET（带参数）请求出错: " + request.error + " , 错误信息: " + response);
            }
        }
    }

    /// <summary>
    /// 发送 GET 请求（无参数）
    /// </summary>
    private IEnumerator SendGetRequestWithoutParams(string url, string token)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            request.SetRequestHeader("Authorization", token);

            yield return request.SendWebRequest();

            string response = request.downloadHandler.text;

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("GET（无参数）请求成功, 返回数据: " + response);

                Machinery machinery = JsonUtility.FromJson<Machinery>(response);

                Debug.Log("All Machinery: " + machinery.data.allMachinery);
            }
            else
            {
                Debug.LogError("GET（无参数）请求出错: " + request.error + " , 错误信息: " + response);
            }
        }
    }
}
